package cn.smbms.service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Service;

import cn.smbms.pojo.ReactiveUser;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@Service
public class ReactiveService implements InitializingBean {
    private final Map<String, ReactiveUser> data = new ConcurrentHashMap<>();
	@Override
	public void afterPropertiesSet() throws Exception {
		data.put("1", new ReactiveUser("1"));
		data.put("2", new ReactiveUser("2"));
	}
    public Flux<ReactiveUser> list() {
        return Flux.fromIterable(this.data.values());
    }

    public Flux<ReactiveUser> getById(final Flux<String> ids) {
        return ids.flatMap(id -> Mono.justOrEmpty(this.data.get(id)));
    }

    public Mono<ReactiveUser> getById(final String id) {
        return Mono.justOrEmpty(this.data.get(id))
                .switchIfEmpty(Mono.error(new Exception()));
    }

    public Mono<ReactiveUser> createOrUpdate(final ReactiveUser user) {
        this.data.put(user.getId(), user);
        return Mono.just(user);
    }

    public Mono<ReactiveUser> delete(final String id) {
        return Mono.justOrEmpty(this.data.remove(id));
    }

}

